package BogoConHandler;

use Socket qw(AF_INET SOCK_STREAM inet_aton sockaddr_in);


use BogoLogger;


use threads; 

use Thread::Queue;

# BConHandler supports connection to server
# and send receive methods
#
sub new{
	my $class = shift;
	my $self = bless{
		INQ => Thread::Queue->new,
		OUTQ => Thread::Queue->new,
		SOCKET => undef,
		TMOUT => 10,
		HOST => undef,
		PROTO => 'tcp',
		PORT => 3456,
		THREAD => undef
	}, $class;
	return $self;
}

sub connectTo{
	my $self = shift;
	BogoLogger->msg(3, "BogoConHandler", $self->{PROTO}."\n");
	
	
	$proto_str = $self->{PROTO};
	$proto = getprotobyname($proto_str);
	
	socket(SOCK, AF_INET, SOCK_STREAM, $proto)
		|| die "socket: $!";
		$inaddr = inet_aton($self->{HOST});
		BogoLogger->msg(3, "BogoConHandler","Socket Created\n");	
		$paddr = sockaddr_in($self->{PORT}, $inaddr);
		eval {
			local $SIG{ALRM} = sub { die "Timeout" };
			alarm $self->{TMOUT}; # x second timeout
			my $val = connect(SOCK, $paddr);
			alarm 0;
			$val;
			} or die "connect: $!";
			
		BogoLogger->msg(3, "BogoConHandler", "Start waiting loop\n");
		$resp = readline(SOCK);
		print $resp;
		$self->{OUTQ}->enqueue($resp);
		BogoLogger->msg(3, "BogoConHandler", "Enqueued msg into Q\n");
		while(my $data = $self->{INQ}->dequeue)	
		{
			BogoLogger->msg(3,"BogoConHandler", "\n".$data);
			if ($data eq 'exit')
			{
				last CLOSE_SOCK;
			}
			syswrite SOCK, $data;
			$resp = readline(SOCK);
			
			BogoLogger->msg(3,"BogoConHandler", $resp."\n");
			$self->{OUTQ}->enqueue($resp);
		}
		CLOSE_SOCK:
			close(SOCK);
}

sub init_connection{
	my $self = shift;
	my ($host, $port, $timeout, $proto) = @_;
	$self->{HOST} = $host;
	$self->{PORT} = $port;
	$self->{TMOUT} = $timeout;
	$self->{PROTO} = $proto;
	BogoLogger->msg(3,"BogoConHandler", "Con Handler inited\n");
	$self->{THREAD} = threads->new(\&connectTo, $self);
	$self->{THREAD}->detach;
	BogoLogger->msg(3,"BogoConHandler", "Thread started [detached](main thread)\n");
	#$self->{THREAD}->join;
}

sub sendDT{
	my $self = shift;
	my $msg = shift;
	$self->{INQ}->enqueue($msg);
	BogoLogger->msg(3,"Sent msg\n");
}
sub recvDT{
	my $self = shift;
	return $self->{OUTQ}->dequeue;
}

sub sendsomething{ 
	
		my $self = shift;
		print "Sending:\n";
		print "GET index.php HTTP/1.1\n";
		
		$self->{INQ}->enqueue("GET index.php HTTP/1.1\n User-Agent: Mozilla/5.0 \n\r\n\r\n");
		print "Sent";
		
		$resp = $self->{OUTQ}->dequeue;
		
		print $resp."\n";
		
		
		
}
 sub DESTROY{
 	BogoLogger->msg(3,"destroy object");
 }
 1;